package com.atguigu.spzx.manner.service.impl;

import com.atguigu.spzx.manner.service.FileUploadService;
import com.atguigu.spzx.manner.util.MinioProperties;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Autowired
    MinioProperties minioProperties;
    @SneakyThrows
    @Override
    public String fileUpload(MultipartFile file) {
        //创建桶
        String time = new DateTime().toString("/yyyy/MM/dd/");
        MinioClient minioClient = MinioClient.builder().
                endpoint(minioProperties.getEndpointUrl()).credentials(minioProperties.getAccessKey(), minioProperties.getSecreKey()).build();
        boolean found=minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
        if (!found){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
        }else {  // 如果存在打印信息
            System.out.println("Bucket 'spzx-bucket' already exists.");
        }
        //参数
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .object("avatar"+time+file.getOriginalFilename())
                .stream(file.getInputStream(),file.getSize(),-1)
                .contentType(file.getContentType())
                .build();
        //上传
        minioClient.putObject(putObjectArgs);

        String fileUrl = minioProperties.getEndpointUrl()+"/"+minioProperties.getBucketName()+"/"+"avatar"+time+file.getOriginalFilename();
        return fileUrl;
    }
}
